package com.blue.core.http;

import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class HttpAsyncInvokerMain
{
	private static Logger logger = LoggerFactory.getLogger(HttpAsyncInvokerMain.class);
	
	public HttpAsyncInvokerMain()
	{
	}
	
	public static void main(String[] args) throws Exception
	{
		HttpAsyncInvoker invoker = new HttpAsyncInvoker();
		String[] urls = {"http://iu.91bihu.com/api/CarInsurance/GetVehicleInfo?MoldName=朗逸牌SVW7167BSD&LicenseNo=粤WGU826&CityCode=14&Agent=81946&CustKey=bihu12321321&SecCode=dce9fe203b45f67317d2f8bf59479c37",
				"http://iu.91bihu.com/api/CarInsurance/CheckVehicle?RegisterDate=2009-02-11&EngineNo=741319&CarType=0&ShowCarType=0&Agent=81946&VehicleNo=DZABCD0004&CityCode=14&VehicleName=朗逸牌SVW7167BSD&CarUsedType=0&CarVin=LSVAB418492184643&CustKey=bihu12321321&SecCode=f8f80b6bbb8d71f5a6c9e41dbdb4f5a3"};
		CountDownLatch latch = new CountDownLatch(urls.length);
		InvokerResult callback = new InvokerResult(latch);
		for (String url : urls)
		{
			invoker.get(url, callback);
			logger.info("请求：{}", url);
		}
		latch.await();
		invoker.destroy();
	}
	
}

class InvokerResult implements FutureCallback<HttpResponse>
{
	private static Logger logger = LoggerFactory.getLogger(InvokerResult.class);
	
	private final CountDownLatch latch;
	
	public InvokerResult(CountDownLatch latch)
	{
		this.latch = latch;
	}

	@Override
	public void completed(HttpResponse response)
	{
		String result = HttpClientUtil.toString(response);
		logger.info("=====================");
		logger.info(result);
		logger.info("=====================");
		latch.countDown();
	}

	@Override
	public void failed(Exception ex)
	{
		latch.countDown();
		ex.printStackTrace();
	}

	@Override
	public void cancelled()
	{
		latch.countDown();
		System.out.println("已取消");
	}
	
}
